<template>
  <div class="main flex width-all">
    <!------------------------------------------ 树 ------------------------------------------------------->

    <div class="tree-view pd10 bg-white mgr20 flex-column">
      <el-input style="width: 240px" v-model="state.customerKeyword" class="mgb10 width-all search" clearable placeholder="客户名或拼音首字母" @keyup.enter="getTreeData">
        <template #append>
          <el-button :icon="Search" @click="filterCustomer" />
        </template>
      </el-input>
      <div class="flex1" style="overflow: auto">
        <TreeVue
          ref="treeEl"
          node-key="customerName"
          :current-node-key="state.currentNodeKey"
          label="customerName"
          :list="state.treeList"
          :expand-on-click-node="false"
          @node-click="onTreeNodeClick"
        />
      </div>
    </div>

    <!------------------------------------------ 表格 ------------------------------------------------------->

    <div class="pd10 bg-white flex1" style="width: calc(100% - 300px)">
      <VxeTableVue
        class="width-all"
        ref="tableEl"
        :on-mounted-query="false"
        :queryFormData="state.formData"
        :column-config="columnConfig"
        data-list-api="/agent/page"
        :show-action-column="false"
        :show-top-add-btn="false"
        :show-top-del-btn="false"
        :show-del-btn="false"
      >
        <!------------------------------------------ 查询 ------------------------------------------------------->

        <template #queryItem>
          <el-form-item label="产线号" prop="productionLineId" class="mgr10">
            <el-input v-model="state.formData.productionLineId" clearable placeholder="产线号" style="width: 160px" />
          </el-form-item>
          <el-form-item label="代理版本" prop="agentVersion" class="mgr10">
            <el-input v-model="state.formData.agentVersion" clearable placeholder="代理版本" style="width: 160px" />
          </el-form-item>
          <el-form-item label="连接状态" prop="agentStatus" class="mgr10">
            <SelectVue
              v-model="state.formData.agentStatus"
              :option-list="[
                { name: '失联', id: '0' },
                { name: '在线', id: '1' }
              ]"
              clearable
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="注册时间" class="mgr10">
            <DatePickVue v-model:start-time="state.formData.params.startTime" v-model:end-time="state.formData.params.endTime" style="width: 220px" />
          </el-form-item>
        </template>

        <!------------------------------------------ 表格列 ------------------------------------------------------->

        <template #agentStatus="{ row }: SlotAgent">
          <el-tag :type="row.agentStatus === '1' ? 'success' : 'danger'">{{ row.agentStatus === '1' ? '在线' : '失联' }}</el-tag>
        </template>

        <template #onlineTotal="{ row }: SlotAgent">
          <div>{{ calDuration(row.createTime, row.agentReportTime) }}</div>
        </template>

        <template #disconnect="{ row }: SlotAgent">
          <div v-if="row.agentStatus === '0'">{{ calDuration(row.agentReportTime, new Date()) }}</div>
        </template>
      </VxeTableVue>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, nextTick, onActivated } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import TreeVue, { type TreeVueInstance } from '@/components/tree'
  import { VxeTableVue, type VxeTableViewInstance } from '@/components/table'
  import DatePickVue from '@/components/date-pick'
  import SelectVue from '@/components/select'
  import { columnConfig } from './config'
  import request, { type IPage } from '@/service'
  import type { SlotAgent, ICustomerEntity } from './config'
  import { Ui, calDuration } from '@/utils'
  import router from '@/router'

  const tableEl = ref<VxeTableViewInstance>()
  const treeEl = ref<TreeVueInstance>()

  const state = reactive({
    currentNodeKey: '客户/全部',
    treeList: [{ id: '1', customerName: '客户/全部', children: [] as ICustomerEntity[] }],
    customerKeyword: '',
    formData: {
      productionLineId: '',
      agentVersion: '',
      agentStatus: '',
      customerName: '',
      params: {
        startTime: '',
        endTime: ''
      }
    }
  })

  let customerList: ICustomerEntity[] = []

  /**----------------------------methods----------------------------------------------------------------------- */

  interface ITreeData {
    node: ICustomerEntity
  }
  const onTreeNodeClick = ({ node }: ITreeData) => {
    state.formData.customerName = node.customerName === '客户/全部' ? '' : node.customerName
    state.currentNodeKey = node.customerName
    reflesh()
  }

  const filterCustomer = () => {
    if (!state.customerKeyword) return (state.treeList[0].children = customerList)
    state.treeList[0].children = customerList.filter(item => item.customerNamePy.includes(state.customerKeyword) || item.customerName.includes(state.customerKeyword))
  }

  const getTreeData = () => {
    request.get<IPage<ICustomerEntity>>('/customer/page', { current: 1, size: 9999, customerStatus: '1' }).then(res => {
      if (res.code !== 0) return Ui.useMessage('error', res.msg)
      customerList = res.data.records
      state.treeList[0].children = customerList
      nextTick(() => {
        treeEl.value?.setCurrentKey(state.currentNodeKey)
      })
    })
  }

  const reflesh = () => {
    tableEl.value?.query()
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */

  getTreeData()

  onActivated(() => {
    const { customerName, agentStatus, startTime, endTime } = router.currentRoute.value.query
    state.formData.customerName = state.formData.customerName ? state.formData.customerName : (customerName as string)
    state.currentNodeKey = (state.formData.customerName ?? '客户/全部') as string
    state.formData.agentStatus = agentStatus as string
    state.formData.params.startTime = startTime as string
    state.formData.params.endTime = endTime as string

    reflesh()
  })
</script>

<style scoped lang="less">
  .main {
    padding: 0;
    background: #f2f6fc;
    .bg-white {
      background: #fff;
    }
  }
</style>
